import React from 'react';
import ReactDOM from 'react-dom';

import './index.less';

interface Toast {
  children?: any;
  text?: any; // 显示内容
  duration?: number; // 显示时间
  [propName: string]: any;
  close?: Function; // 关闭提示
  style?: Object; // 样式
  type?: string; // 提示类型
}
const Toast = (props: Toast) => {
  // console.log('Toast-props', props.type);
  return (
    <div className={`c-toast fx fx-ai-c fx-jc-sb ${props.type}`} style={props.style}>
      <div className="text">{props.text}</div>
      <span className="close" onClick={() => (props.close as Function)()}>
        X
      </span>
    </div>
  );
};

export default (obj: Toast) => {
  const { duration } = obj;
  let timer: any = null;
  // 关闭提示弹框
  const close = () => {
    clearTimeout(timer);
    document.body.removeChild(_div);
  };

  const _div = document.createElement('div');
  document.body.appendChild(_div);
  ReactDOM.render(<Toast {...obj} close={close}></Toast>, _div);
  
  timer = setTimeout(() => {
    document.body.removeChild(_div);
  }, duration || 2000);
};
